<template>
  <div>
    <a-card>
      <a-form :form="form">
        <a-row>
          <a-col :md="20" :sm="24">
            <a-col :md="12" :sm="24">
              <a-form-item
                label="导师编号"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['dsbh',
                  {
                    rules: [{ required: true, message: '请输入导师编号，输入类型为纯数字!', pattern: /^[0-9]+$/ }],
                  }]" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="姓名"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['xm',
                  {
                    rules: [{ required: true, message: '请输入导师姓名，输入类型为纯中文!', pattern: /^[\u4E00-\u9FFF]+$/}],
                  }]" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="性别"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select allowClear v-decorator="['xbm',
                  {
                    rules: [{ required: true, message: '请选择性别!', }],
                  }]">
                  <a-select-option v-for="i in TYPE0011" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="身份证"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input @change="zjhmChange" v-decorator="['sfzjh',
                  {
                    rules: [{ required: true, message: '请输入正确的身份证！',
                    pattern: /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/ }],
                  }]" :maxLength="18" />
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="出生日期"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-date-picker v-decorator="['csrq',
                  {
                    rules: [{ required: true, message: '请选择出生日期!' }],
                  }]" style="width: 100%" format="YYYY-MM-DD"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="院系"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select v-decorator="['dwh',
                  {
                    rules: [{ required: true, message: '请选择院系' }],
                  }]" showSearch :filterOption="filterOption" @change="yxChange">
                  <a-select-option v-for="i in selectMenu.yx" :key="i.id" :value="i.dwh">{{ i.dwh }} {{ i.dwmc }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="专业"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select v-decorator="['zyh',
                  {
                    rules: [{ required: true, message: '请选择专业' }],
                  }]" showSearch :filterOption="filterOption">
                  <a-select-option v-for="i in selectMenu.zy" :key="i.id" :value="i.zyh">{{ i.zyh }} {{ i.zymc }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="职称"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-select v-decorator="['zc',
                  {
                    rules: [{ required: true, message: '请选择职称' }],
                  }]">
                  <a-select-option v-for="i in HWXNYJYZC" :key="i.id" :value="i.code">{{ i.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="电子邮箱"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['dzxx',
                  {
                    rules: [{ required: true, message: '请输入正确的电子信箱', pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/}],
                  }]"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="手机号码"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['lxdh',
                  {
                    rules: [{ required: true, message: '请输入正确的手机号码', pattern: /^[1](([3][0-9])|([4][5-9])|([5][0-3,5-9])|([6][5,6])|([7][0-8])|([8][0-9])|([9][1,8,9]))[0-9]{8}$/}],
                  }]"  :maxLength="11"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="固定电话"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input :maxLength="13" v-decorator="['zzdh',{
                    rules: [{ required: false, message: '请输入不超过4位的区号数字和8位纯数字的固定电话', pattern: /0\d{2,3}-\d{7,8}/}],
                  }]"/>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item
                label="研究方向"
                :labelCol="{span: 7,offset: 1}"
                :wrapperCol="{span: 15, offset: 1}"
              >
                <a-input v-decorator="['yjfx',
                  {
                    rules: [{ required: true, message: '请输入研究方向' }],
                  }]"/>
              </a-form-item>
            </a-col>
          </a-col>
          <a-col :md="4" :sm="24">
            <a-form-item
              label=""
              :labelCol="{span: 0,offset: 1}"
              :wrapperCol="{span: 20, offset: 1}"
              selfUpdate
            >
              <a-upload
                name="avatar"
                style="width:120px;height:120px;"
                listType="picture-card"
                class="avatar-uploader"
                :showUploadList="false"
                :action="uploadUrl"
                list-type="picture"
                :headers="{
                  Authorization: $store.state.account.token
                }"
                @change="handleChange"
              >
                <img v-if="imageUrl" :src="imageUrl" style="width: 200px;height: 200px;" alt="avatar" />
                <div v-else>
                  <a-icon :type="loading ? 'loading' : 'plus'" />
                  <div class="ant-upload-text">上传照片</div>
                </div>
              </a-upload>
              <a-input v-decorator="['zpdz']" type="hidden"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-card>


    <div class="ant-pro-footer-toolbar">
      <a-button style="float: right;margin-top: 10px;" @click="creatTeacher" :loading="loadingBtn" type="primary">保存</a-button>
    </div>
  </div>
</template>
<script>
import { mapState } from 'vuex'
import moment from 'moment'
import ACol from "ant-design-vue/es/grid/Col";
const selectArr = ['TYPE0320', 'TYPE0321', 'TYPE0011', 'TYPE0360', 'HWXNYJYZC', 'TYPE0018', 'TYPE0023']
function getBase64 (img, callback) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result))
  reader.readAsDataURL(img)
}
export default {
  data () {
    return {
      selectMenu: {},
      uploadUrl:`${process.env.SERVICE_URL}upload/img`,
      loading: false,
      imageUrl: '',
      loadingBtn: false,
      dsbh: '',
      zsnd: ''
    }
  },
  components: {ACol},
  beforeCreate () {
    this.form = this.$form.createForm(this)
  },
  computed: {
    ...mapState({
      systemInfo: state => state.app.systemInfo,
      TYPE0321: state => state.app['TYPE0321'], // 是否在岗
      TYPE0011: state => state.app['TYPE0011'], // 性别
      TYPE0320: state => state.app['TYPE0320'], // 导师状态
      TYPE0360: state => state.app['TYPE0360'], // 导师类别
      HWXNYJYZC: state => state.app['HWXNYJYZC'], // 职称
      TYPE0018: state => state.app['TYPE0018'], // 学历
      TYPE0023: state => state.app['TYPE0023'] // 学位
    })
  },
  created () {
    selectArr.forEach(v => {
      this.$store.dispatch('app/setDictionary', v)
    })
    this.$store.dispatch('app/sysInfo').then(res => {
      this.zsnd = this.systemInfo.masterAdmissionYear
    })
    this.initSelectMenu()
  },
  methods: {
    initSelectMenu () {
      let allRequest = [
        this.$api.base.collegeAll(),
        this.$api.base.areaList()
      ]
      Promise.all(allRequest).then(res => {
        this.selectMenu = {
          yx: res[0].data,
          province: res[1].data
        }
      })
    },
    yxChange (code) {
      // this.$set(this.queryParam, 'zy', '')
      if (code) {
        this.$api.base.majorAll({lsdwh: code}).then(res => {
          this.$set(this.selectMenu, 'zy', res.data)
        })
      } else {
        this.$set(this.selectMenu, 'zy', [])
      }
    },
    searchStaff () {
      let bh = this.form.getFieldValue('jzgbh')
      this.dsbh = bh
      this.$api.teacher.teacherStaffInfo(bh).then(res => {
        if (res.data && res.data.rdpzny) {
          res.data.rdpzny = moment(res.data.rdpzny)
        }
        if (res.data && res.data.scrbdny) {
          res.data.scrbdny = moment(res.data.scrbdny)
        }
        if (res.data && res.data.scrsdny) {
          res.data.scrsdny = moment(res.data.scrsdny)
        }
        if (res.data && res.data.dslbm) {
          res.data.dslbm = res.data.dslbm.split(',')
        }
        // if (['rdpzny', 'scrbdny', 'scrsdny'].includes(key) && values[key]) {
        //   values[key] = values[key].format('YYYYMM')
        // }
        if (res.data.byxxszsf) {
          this.handlePChange(res.data.byxxszsf)
        }
        this.form.setFieldsValue(res.data)
        this.form.setFieldsValue({dsbh: res.data.gh})
        if (!res.data || !res.data.gh) {
          this.form.setFieldsValue({dsbh: bh})
        }
        console.log(res)
      }).catch(() => {
        console.log(1)
        this.form.resetFields()
        this.form.setFieldsValue({dsbh: bh})
      })
    },
    handleChange (info) {
      if (info.file.status === 'uploading') {
        this.loading = true
        return
      }
      if (info.file.status === 'done') {
        let path = info.file.response.data[0]
        this.form.setFieldsValue({zpdz: path})
        this.imageUrl = `${process.env.IMG_URL}${path}`
      }
    },
    beforeUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      if (!isJPG) {
        this.$message.error('You can only upload JPG file!')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJPG && isLt2M
    },
    handlePChange(v) {
      this.form.setFieldsValue({byxxdm: ''})
      this.$api.base.schoolInfoQueryAll({xzqhsdm: v}).then(res => {
        this.$set(this.selectMenu, 'schoolList' , res.data)
      })
    },
    filterOption (value, op) {
      return op.componentOptions.children[0].text.indexOf(value) !== -1
    },
    setData (option, key) {
      this.form.setFieldsValue({[key]: option.data.attrs.name})
    },
    creatTeacher () {
      this.form.validateFields((err, values) => {
        if (err) {
          return
        }
        try {
          this.loadingBtn = true
          for (const key in values) {
            if (['rdpzny', 'scrbdny', 'scrsdny'].includes(key) && values[key]) {
              values[key] = values[key].format('YYYYMM')
            }
          }
          this.$DateToString(values)
          console.log(values)
          // values.dslbm = values.dslbm.join(',')
          // values.dszdzyList = this.$refs.guideMajor.dszdzyList.map(item => {
          //   return {
          //     ...item
          //   }
          // })
          // values.dszdzyList.forEach(zy => {
          //   delete zy.researchList
          //   zy.dsyjfxList = zy.dsyjfxList && zy.dsyjfxList.map(item => {
          //     return {
          //       yjfxm: item
          //     }
          //   })
          // })
          this.$message.loading('保存中', 0)
          this.$api.overseas.addTeacher(values).then(res => {
              this.$message.success(res.msg)
              setTimeout(() => {
                this.form.resetFields()
                this.imageUrl = ''
                this.loading = false
              }, 2000)
          }).finally(() => {
            setTimeout(() => {
              this.$message.destroy()
            }, 4000);
            this.loadingBtn = false
            // this.form.resetFields()
          })
        } catch (error) {
          console.log(error)
        }
      })
    },
   zjhmChange(v){
      // let sfzjlxm = this.form.getFieldValue('sfzjh');
      console.log(v)
      const {value} = v.target;
      if(value && (value.length === 15 || value.length === 18)){//居民省份证
        this.form.setFieldsValue({"csrq":moment(this.getBirthdatByIdNo(value), 'YYYY-MM-DD')});
        // this.form.setFieldsValue({"nl": });
        console.log(this.form.getFieldsValue().csrq)
        // this.getAgeFromBirthday(this.form.getFieldsValue().csrq)
      }
    },
    //获取出生日期
    getBirthdatByIdNo (IdNO){
      let birthday = "";
      console.log(IdNO)
      if (IdNO.length==18) {
        birthday = IdNO.substr(6,8);
        return birthday.replace(/(.{4})(.{2})/,"$1-$2-");
      }else if(IdNO.length==15){
        birthday = "19"+IdNO.substr(6,6);
        return birthday.replace(/(.{4})(.{2})/,"$1-$2-");
      }else{
        return "";
      }
    },

  }
}
</script>
<style lang="less" scoped>
  /deep/ .ant-form-item-label {
      text-align: left;
      padding-left: 50px;
  }
</style>
